﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using IDM.BF.AdministrationService;
using Sio.Mdm.Client;
using Sio.Mdm.Types;
using Ext.Net;
using Sio.Mdm.Entities;
using System.Collections.Generic;
using IDM.Types;

namespace IDM.Web
{
    public partial class _Default : Sio.Mdm.Web.Controls.Page
    {
        #region Definitions
        enum LoadMode
        {
            Users,
            Roles,
            Tokens
        } 
        #endregion

        public _Default()
        {
            LoadContext = LoadMode.Users;
        }

        private LoadMode LoadContext
        {
            get
            {
                return (LoadMode)ViewState["__loadMode"];
            }
            set
            {
                ViewState["__loadMode"] = value;
            }
        }
        private string NodeID
        {
            get
            {
                return (string)ViewState["__nodeID"];
            }
            set
            {
                ViewState["__nodeID"] = value;
            }
        }

        #region Methods

        #region Protected

        #region OnLoad
        protected override void OnLoad(EventArgs e)
        {
            if (!ExtNet.IsAjaxRequest && UserSession != null)
            {
                UserButton.Text = UserSession.UporabniskoIme;
            }

            base.OnLoad(e);
        } 
        #endregion

        #region NodeSelected
        protected void NodeSelected(object sender, DirectEventArgs args)
        {
            LoadMode mode = LoadMode.Users;
            string context = args.ExtraParams["parent"];
            string nodeId = args.ExtraParams["node"];

            if (string.IsNullOrEmpty(context))
            {
                if (nodeId == "RolesNode")
                {
                    mode = LoadMode.Roles;
                }
                else if (nodeId == "TokensNode")
                {
                    mode = LoadMode.Tokens;
                }
            }
            else
            {
                if (context == "token")
                {
                    mode = LoadMode.Tokens;
                }
                else if (context == "role")
                {
                    mode = LoadMode.Roles;
                }
            }

            LoadContext = mode;
            NodeID = nodeId;

            Result error = null;

            switch (mode)
            {
                case LoadMode.Roles:
                    error = LoadRolesList(args, nodeId);
                    break;
                case LoadMode.Tokens:
                    error = LoadTokensList(args, nodeId);
                    break;
                case LoadMode.Users:
                    error = LoadUsersList(args);
                    break;
            }

            if (error != null)
            {
                args.Success = false;
                args.ErrorMessage = error.ToString();
            }
        } 
        #endregion

        #region LoadNode
        protected void LoadNode(object sender, NodeLoadEventArgs args)
        {
            LoadMode mode = LoadMode.Users;
            string context = args.ExtraParams["parent"];

            if (string.IsNullOrEmpty(context))
            {
                if (args.NodeID == "RolesNode")
                {
                    mode = LoadMode.Roles;
                }
                else if (args.NodeID == "TokensNode")
                {
                    mode = LoadMode.Tokens;
                }
            }
            else
            {
                if (context == "token")
                {
                    mode = LoadMode.Tokens;
                }
                else if (context == "role")
                {
                    mode = LoadMode.Roles;
                }
            }

            Result error = null;

            switch (mode)
            {
                case LoadMode.Roles:
                    error = LoadRolesTree(args);
                    break;
                case LoadMode.Tokens:
                    error = LoadTokensTree(args);
                    break;
                case LoadMode.Users:
                    break;
            }

            if (error != null)
            {
                args.Success = false;
                args.ErrorMessage = error.ToString();
            }
        }   
        #endregion

        #region Logout
        protected void Logout(object sender, EventArgs args)
        {
            FormsAuthentication.SignOut();
            Session.Clear();
            Response.Redirect("Login.aspx");
        } 
        #endregion

        #region DeleteItem
        protected void DeleteItem(object sender, DirectEventArgs e)
        {
            if (e.ExtraParams["node"] == "UsersNode")
            {
                string json = e.ExtraParams["selected"];
                Dictionary<string, string>[] rows = JSON.Deserialize<Dictionary<string, string>[]>(json);

                foreach (Dictionary<string, string> row in rows)
                {
                    foreach (KeyValuePair<string, string> vals in row)
                    {
                        if (vals.Key == "ID")
                        {
                            int ID = Int32.Parse(vals.Value);
                            Types.User user = EntityFactory.CreateInstance<User>();

                            user.Load(ID);
                            user.Delete();
                        }
                    }
                }
            }
        } 
        #endregion

        #region StoreReload
        protected void StoreReload(object sender, StoreRefreshDataEventArgs e)
        {
            DirectEventArgs args = new DirectEventArgs(new Ext.Net.ParameterCollection());

            args.ExtraParams.Add(new Ext.Net.Parameter("parent", NodeID));
            Result error = null;

            switch (LoadContext)
            {
                case LoadMode.Roles:
                    error = LoadRolesList(args, NodeID);
                    break;
                case LoadMode.Tokens:
                    error = LoadTokensList(args, NodeID);
                    break;
                case LoadMode.Users:
                    error = LoadUsersList(args);
                    break;
            }

            if (error != null)
            {
                args.Success = false;
                args.ErrorMessage = error.ToString();
            }
        } 
        #endregion

        #endregion

        #region Private
        private Result LoadRolesTree(NodeLoadEventArgs args)
        {
            EntityCollection<Role> roles = new EntityCollection<Role>();
            Criteria criteria = new Criteria();

            if (args.NodeID == "RolesNode")
            {
                criteria.Query.SetExpression(new QueryParameter("ParentID"));
            }
            else
            {
                int nodeId = Int32.Parse(args.NodeID.Remove(0, 5));
                criteria.Query.SetExpression(new QueryParameter("ParentID", nodeId));
            }
            
            if (roles.Load(criteria))
            {
                RegisterIcon(Icon.GroupKey);

                foreach (Role role in roles)
                {
                    AsyncTreeNode node = new AsyncTreeNode();

                    node.NodeID = String.Format("Role_{0}", role.ID);
                    node.Text = role.Name;
                    node.Icon = Icon.GroupKey;                    
                    node.CustomAttributes.Add(new ConfigItem("ctx", "role", ParameterMode.Value));

                    args.Nodes.Add(node);
                }
            }

            return roles.Error;
        }
        private Result LoadTokensTree(NodeLoadEventArgs args)
        {
            EntityCollection<Token> tokens = new EntityCollection<Token>();
            Criteria criteria = new Criteria();

            if (args.NodeID == "TokensNode")
            {
                criteria.Query.SetExpression(new QueryParameter("ParentID"));
            }
            else
            {
                int nodeId = Int32.Parse(args.NodeID.Remove(0, 6));
                criteria.Query.SetExpression(new QueryParameter("ParentID", nodeId));
            }

            if (tokens.Load(criteria))
            {
                foreach (Token token in tokens)
                {
                    AsyncTreeNode node = new AsyncTreeNode();

                    node.NodeID = String.Format("Token_{0}", token.ID);
                    node.Text = token.Name;
                    node.Icon = Icon.Key;                    
                    node.CustomAttributes.Add(new ConfigItem("ctx", "token", ParameterMode.Value));

                    args.Nodes.Add(node);
                }
            }

            return tokens.Error;
        }
        private Result LoadUsersList(EventArgs arg)
        {
            // ==> change by Matej
            EntityCollection<User> users = new EntityCollection<User>(); // (r => r.ID != null);
            
            users.Select(r => r.ID != null);
            users.TotalCount.ToString();
            //EntityCollection<User> users = new EntityCollection<User>();
            //users.Load(Criteria.Empty);
            GridStore.DataSource = users;
            GridStore.DataBind();

            return users.Error;
        }

        protected void ImeFunkcije(Object sender, DirectEventArgs arg)
        {
          //  throw new NotImplementedException();
        }

        private Result LoadRolesList(DirectEventArgs args, string nodeID)
        {
            EntityCollection<Role> roles = new EntityCollection<Role>();
            Criteria critera = new Criteria();

            if (args.ExtraParams["parent"] == null)
            {
                critera.Query.SetExpression(new QueryParameter("ParentID"));
            }
            else
            {
                int nodeId = Int32.Parse(nodeID.Remove(0, 5));
                critera.Query.SetExpression(new QueryParameter("ParentID", nodeId));
            }
            
            roles.Load(critera);
            GridStore.DataSource = roles;
            GridStore.DataBind();

            return roles.Error;
        }
        private Result LoadTokensList(DirectEventArgs args, string nodeID)
        {
            EntityCollection<Token> tokens = new EntityCollection<Token>();
            Criteria criteria = new Criteria();

            if (args.ExtraParams["parent"] == null)
            {
                criteria.Query.SetExpression(new QueryParameter("ParentID"));
            }
            else
            {
                int nodeId = Int32.Parse(nodeID.Remove(0, 6));
                criteria.Query.SetExpression(new QueryParameter("ParentID", nodeId));
            }

            tokens.Load(criteria);
            GridStore.DataSource = tokens;
            GridStore.DataBind();

            return tokens.Error;
        }
        #endregion

        #endregion
    }
}
